package com.diankangwo.controller;

import cn.beecloud.bean.BCOrder;
import com.diankangwo.constant.resultMsg;
import com.diankangwo.dao.OrderDAO;
import com.diankangwo.dao.UserDAO;
import com.diankangwo.domain.Order;
import com.diankangwo.domain.UserInfo;
import com.diankangwo.dto.PayConfigurationDTO;
import com.diankangwo.service.OrderMomentPayService;
import com.diankangwo.service.PayManagementService;
import com.diankangwo.util.BeecloudPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付控制器
 */
@Controller
@Api(description = "支付")
@RequestMapping(value = "/pay")
public class PayController {
    @Autowired
    private PayManagementService payManagementService;
    private static final Log LOG = LogFactory.getLog(PayController.class);
    @Autowired
    private UserDAO userDao;
    @Autowired
    private OrderMomentPayService orderMomentPayService; // 在线支付
    @Autowired
    private OrderDAO orderDAO;
    private BeecloudPayUtil util = new BeecloudPayUtil();

    /**
     * 支付宝网页支付
     *
     * @param orderId     订单号
     * @param totalFee    金额
     * @param optional    附加数据<选填>
     * @param accessToken token
     * @return
     */
    @ApiOperation(value = " 获取端口列表", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "totalFee", value = "金额", required = true, dataType = "String"),
            @ApiImplicitParam(name = "optional", value = "附加数据", required = false, dataType = "Map<String, Object>"),
            @ApiImplicitParam(name = "orderId", value = "订单号", required = true, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/aliweb", method = RequestMethod.POST)
    public String aliwebPay(@NotBlank String orderId, @NotNull Integer totalFee, Map<String, Object> optional, String accessToken) {
        String code = "2";
        String msg = "操作异常！";
        String returnUrl = "";
        if (userDao.getUserByToken(accessToken) != null) {
            returnUrl = orderMomentPayService.aliPay(orderId, totalFee, optional);
            LOG.debug("阿里网页支付URL - " + returnUrl);
            msg = "请求成功！";
            code = "1";
        } else {
            msg = "获取用户信息失败！";
        }
        return resultMsg.mapToJson(code, msg, returnUrl);
    }

    /**
     * 阿里移动网页支付
     *
     * @param orderId     缴费单ID
     * @param totalFee    缴费金额，单位为分
     * @param accessToken token
     * @return
     */
    @ApiOperation(value = " 获取端口列表", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "totalFee", value = "金额", required = true, dataType = "String"),
            @ApiImplicitParam(name = "orderId", value = "订单号", required = true, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/aliwap", method = RequestMethod.POST)
    public String aliwappay(@NotBlank String orderId, @NotNull Integer totalFee, String accessToken) {
        String code = "2";
        String msg = "操作异常！";
        String returnUrl = orderMomentPayService.aliwapPay(orderId, totalFee, "getUrl");
        LOG.debug("阿里移动支付URL - " + returnUrl);
        return resultMsg.mapToJson(code, msg, returnUrl);
    }

    /**
     * 微信扫码支付
     *
     * @param orderId
     * @param totalFee
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/wxqr", method = RequestMethod.POST)
    public String wechatQrsPay(@NotBlank String orderId, @NotNull Integer totalFee) {
        String code = "2";
        String msg = "操作异常！";
        String returnUrl = orderMomentPayService.wxqrPay(orderId, totalFee);
        String billNo = payManagementService.queryById(Integer.parseInt(orderId)).getBillNo();
        return resultMsg.mapToJson(code, msg, returnUrl);
    }

    /**
     * WEB
     * 微信扫码支付
     *
     * @param orderId
     * @param totalFee
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/wxqrweb", method = RequestMethod.POST)
    public String wechatQrsPayweb(@NotBlank String orderId, @NotNull Integer totalFee) {
        String code = "2";
        String msg = "操作异常！";
        String returnUrl = orderMomentPayService.wxqrPay(orderId, totalFee);
        String billNo = payManagementService.queryById(Integer.parseInt(orderId)).getBillNo();
        return resultMsg.mapToJson(code, msg, returnUrl);
    }

    /**
     * 银联网页支付
     *
     * @param orderId
     * @param totalFee
     * @return html
     */
    @ResponseBody
    @RequestMapping(value = "union", method = RequestMethod.POST)
    public String unionPay(HttpServletRequest request, HttpServletResponse response, @NotBlank String orderId, @NotNull Integer totalFee) {
        String code = "2";
        String msg = "操作异常！";
        String returnHtml = orderMomentPayService.unionWebPay(orderId, totalFee);
        return resultMsg.mapToJson(code, msg, returnHtml);
    }

    /**
     * 银联移动支付
     *
     * @param orderId
     * @param totalFee
     * @return html
     */
    @ResponseBody
    @RequestMapping(value = "unionWap", method = RequestMethod.POST)
    public String unionWapPay(HttpServletRequest request, HttpServletResponse response, @NotBlank String orderId, @NotNull Integer totalFee) {
        String code = "2";
        String msg = "操作异常！";
        String returnHtml = orderMomentPayService.unionWapPay(orderId, totalFee);
        return resultMsg.mapToJson(code, msg, returnHtml);
    }


    /**
     * 支付宝APP+微信APP支付
     *
     * @param accessToken token
     * @param payType     支付方式
     * @param orderNo     订单号
     * @return
     */
    @ApiOperation(value = " 支付宝APP+微信APP支付", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "accessToken", required = true, dataType = "String"),
            @ApiImplicitParam(name = "payType", value = "支付类型", required = true, dataType = "String"),
            @ApiImplicitParam(name = "orderNo", value = "订单号", required = true, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/getinfo", method = RequestMethod.GET)
    public String getPayInfo(String accessToken, String payType, String orderNo, String idCard, String name, String portID, String tel) {
        String code = "2";
        String msg = "操作异常！";
        UserInfo user = userDao.getUserByToken(accessToken);
        Order order = new Order();
        BCOrder bcOrder = new BCOrder();
        Map<String, Object> optional = new HashMap<String, Object>();
        if (user != null) {
            order = orderDAO.findByOrderNo(orderNo);
        } else {
            msg = "未查询到用户登录信息！";
        }
        String cName = "";
        if (payType.equals("ALI_APP")) {
            if (order.getType().equals("port")) {
                cName = "申请端口";
                optional.put("type", "port");
                optional.put("tel", tel);
                optional.put("idCard", idCard);
                optional.put("name", name);
                optional.put("userId", user.getId());
                optional.put("portId", portID);
                optional.put("orderNo", orderNo);
            } else if (order.getType().equals("commodity")) {
                cName = order.getShoppingCarts().get(0).getCommodityName();
            } else if (order.getType().equals("userget")) {
                cName = "用户充值";
                optional.put("orderNo", orderNo);
                optional.put("userId", user.getId());
                optional.put("type", "userWallet");
            }
            if (cName.length() > 13) {
                cName = cName.substring(0, 13) + "...";
            }
            order.setPayType("ALI_APP");
            orderDAO.saveOrUpdate(order);
            bcOrder = util.aliPayApp(order.getTotalFee(), order.getOrderNo(), cName, optional);
            code = "1";
            msg = "操作成功！";
        } else if (payType.equals("WX_APP")) {
            if (order.getType().equals("commodity")) {
                cName = order.getShoppingCarts().get(0).getCommodityName();
            } else if (order.getType().equals("userget")) {
                cName = "用户充值";
                optional.put("orderNo", orderNo);
                optional.put("type", "userWallet");
                optional.put("userId", user.getId());
            }
            if (cName.length() > 13) {
                cName = cName.substring(0, 13) + "...";
            }
            order.setPayType("WX_APP");
            orderDAO.saveOrUpdate(order);
            bcOrder = util.weAppPay(order.getTotalFee(), order.getOrderNo(), cName);
            code = "1";
            msg = "操作成功！";
        }
        return resultMsg.mapToJson(code, msg, bcOrder);
    }

    /**
     * 获取支付配置信息
     *
     * @param accessToken
     * @return
     */
    @ApiOperation(value = " 获取支付配置信息", notes = "")
    @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String")
    @ResponseBody
    @RequestMapping(value = "/configuration", method = RequestMethod.GET)
    public String configuration(String accessToken) {
        String code = "2";
        String msg = "操作异常！";
        PayConfigurationDTO pcd = null;
        if (userDao.getUserByToken(accessToken) != null) {
            pcd = new PayConfigurationDTO();
            pcd.setAppSecret("");
            pcd.setMasterSecret("");
            pcd.setTestSecret("");
            code = "1";
            msg = "获取成功！";
        } else {
            msg = "未获取到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, pcd);
    }
}
